import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     *
     * @param head ListNode类
     * @param m int整型
     * @param n int整型
     * @return ListNode类
     */
    public ListNode reverseBetween(ListNode head, int m, int n) {
        Stack<ListNode> stack = new Stack<>();
        ListNode cur = head;
        ListNode prev = null;
        int len = 1;

        // 找到第m个节点的前一个节点
        while (len < m && cur != null) {
            prev = cur;
            cur = cur.next;
            len++;
        }

        // 反转从第m个到第n个节点
        while (len <= n && cur != null) {
            stack.push(cur);
            cur = cur.next;
            len++;
        }

        // 反转链表部分
        ListNode newHead = stack.pop();
        ListNode node = newHead;
        while (!stack.isEmpty()) {
            node.next = stack.pop();
            node = node.next;
        }
        node.next = cur; // 连接反转部分的后继节点

        // 如果m不是1，则需要连接前驱节点
        if (prev != null) {
            prev.next = newHead;
        } else {
            // 如果m是1，则反转部分是新的头节点
            head = newHead;
        }

        return head;
    }


    public static void main(String[] args) {
        Solution solution = new Solution();
        ListNode head = new ListNode(1);
        ListNode cur = head;
        for (int i = 2; i <= 2; i++) {
            ListNode node = new ListNode(i);
            cur.next = node;
            cur = cur.next;
        }
        System.out.println(solution.reverseBetween(head, 1, 2));
    }
}